package com.cw.filter;


import com.alibaba.fastjson2.JSONObject;
import com.cw.pojo.Result;
import com.cw.utils.JwtUtils;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import java.io.IOException;

@Slf4j
//@WebFilter(urlPatterns = "/*")
public class LoginCheckFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse resp = (HttpServletResponse) servletResponse;
        //获取请求URL
        StringBuffer requestURL = req.getRequestURL();
        log.info("请求URL:{}", requestURL);

        //判断请求url是否包含login
        if (requestURL.indexOf("login") != -1) {
            log.info("登录操作,放行...");
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }

        //获取请求头中的令牌(token)
        String token = req.getHeader("token");

        //判断令牌是否存在,如果不存在,返回错误结果
        if (!StringUtils.hasLength(token)) {
            log.info("token为空,返回未登录的信息");
            Result error = Result.error("NOT_LOGIN");
            //此前均是在Controller中直接转换,因为有@RestController注解
            //此处需要手动转换对象 --json(阿里巴巴fastJSON)
            String notLogin = JSONObject.toJSONString(error);//将对象转为json格式的字符串
            resp.getWriter().write(notLogin);//将字符串响应给浏览器
            return;
        }

        //解析令牌,如果解析失败,返回错误结果(未登录)
        try {
            JwtUtils.parseClaim(token); //快捷键ctrl+alt+t
        } catch (Exception e) {
            e.printStackTrace();
            log.info("解析令牌失败,返回未登录错误信息");
            Result error = Result.error("NOT_LOGIN");
            //此前均是在Controller中直接转换,因为有@RestController注解
            //此处需要手动转换对象 --json(阿里巴巴fastJSON)
            String notLogin = JSONObject.toJSONString(error);//将对象转为json格式的字符串
            resp.getWriter().write(notLogin);//将字符串响应给浏览器
            return;

        }
        //放行
        log.info("令牌合法,放行");
        filterChain.doFilter(servletRequest, servletResponse);
    }
}
